﻿#include "CServer.h"
#include <QDataStream>
#include <QThread>

CServer::CServer()
{
}

CServer::~CServer()
{
}

bool CServer::init()
{
    if (nullptr != m_pClientSocket)
    {
        connect(m_pClientSocket,SIGNAL(readyRead()),this,SLOT(slot_ReadyRead()));
        connect(m_pClientSocket,SIGNAL(connected()),this,SLOT(slot_Connected()));
        connect(m_pClientSocket,SIGNAL(disconnected()),this,SLOT(slot_Disconnected()));
        connect(m_pClientSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(slot_Error(QAbstractSocket::SocketError)));

        if(!m_sServerConfig.bConfiged)
        {
            qDebug()<< "Not configed";
            return false;
        }
        m_strWorkDir = m_sServerConfig.strWorkDir;

        return true;
    }
    return false;
}

int CServer::listenClient()
{
    QString strUserName;
    if(!waitMessage("USER"))
    {
        return -1;
    }
    strUserName = m_strArg;

    QString strPassWord;
    waitMessage("PASS");
    strPassWord = m_strArg;
    if(strUserName == m_sServerConfig.strUserName && strPassWord == m_sServerConfig.strPassWord)
    {
        emit sig_sendMessage("Login success. Welcome to myFTPServer. Author: WangXueFeng.Robert");
    }
    else
    {
        emit sig_sendMessage("Login failed.");
        return -1;
    }

    while(true)
    {
        if (true == m_bRecvData && "" != m_strRecvData)
        {
            m_bRecvData = false;
            m_strRecvData = "";
        }
        else
        {
            qDebug()<<"wait CMD.";
            QThread::sleep(2);
            continue;
        }

        if(m_strCMD == "PWD")
        {
            emit sig_sendMessage("is the current directory");
            continue;
        }
        if(m_strCMD == "SIZE")
        {
            emit sig_sendMessage("Size = 1024.");
            continue;
        }
        if(m_strCMD == "QUIT")
        {
            emit sig_sendMessage("ByeBye");
            break;
        }
    }

    qDebug() << "client quit.";
    return 0;
}

bool CServer::waitMessage(QString str)
{
    QString strData = "";
    while(true)
    {
        if (true == m_bRecvData && "" != m_strRecvData)
        {
            strData = m_strRecvData;
            m_bRecvData = false;
            m_strRecvData = "";
            break;
        }
        else
        {
            qDebug()<<"wait Message.";
            QThread::sleep(2);
            continue;
        }
    }
    if(!strData.contains(str))
    {
        return false;
    }
    else
    {
        return true;
    }
}

void CServer::slot_ReadyRead()
{
    QObject *obj = this->sender();
    QTcpSocket *pClientSocket = qobject_cast<QTcpSocket *>(obj);
    if (nullptr == pClientSocket)
    {
        return;
    }

    qint64 sizeNow = 0;
    do
    {
        //当前缓冲区里面数据的大小，即：收到的数据大小
        sizeNow = pClientSocket->bytesAvailable();
        QDataStream stream(pClientSocket);

        if(m_iSizePackLast == 0)
        {
            if(sizeNow < sizeof(qint32))
            {
                return;
            }

            stream>>m_iSizePackLast;
        }
        //当满足条件时，说明包没有被完整接收，故，继续等待。
        if(sizeNow < m_iSizePackLast-4)
        {
            return;
        }

        QByteArray dataFull;
        stream>>dataFull;

        m_iSizePackLast = 0;

        //剩余的字节数，以此来判断是否产生粘包的问题
        sizeNow = pClientSocket->bytesAvailable();

        QString strData(dataFull);
        m_strRecvData = strData;
        QVector<QString> vec;
        //收到的客户端发来的数据，其数据格式为：“命令:命令参数”
        if (m_strRecvData.contains(":"))
        {
            vec = m_strRecvData.split(":").toVector();
            if (2 == vec.size())
            {
                m_strCMD = vec[0];
                m_strArg = vec[1];
            }
        }
        qDebug()<<"received data is "<<m_strRecvData;
        m_bRecvData = true;
    }
    while(sizeNow>0);
}

//连接成功
void CServer::slot_Connected()
{
    qDebug()<<"connect sucess.";
}

//连接断开
void CServer::slot_Disconnected()
{
    QObject *obj = this->sender();
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(obj);
    socket->deleteLater();
    qDebug()<<"connect failed.";
}

//出错
void CServer::slot_Error(QAbstractSocket::SocketError socketError)
{
    qDebug()<<"error"<<socketError;
}
